package com.cy.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.cy.bean.GameList;
import com.cy.util.ConnectionFactory;

public class GameListDaoImpl implements GameListDao {

	@Override
	public List<GameList> findAllByPage(int page, String namevalue) {
		Connection conn = ConnectionFactory.getConnection();
		PreparedStatement psmt = null;
		ResultSet rs = null;
		try {
			if (namevalue == null || namevalue.equals("")) {
				String sql = "select * from games limit ?,8";
				psmt = conn.prepareStatement(sql);
				psmt.setInt(1, page);
			} else if (namevalue != null && !namevalue.equals("")) {
				String sql = "select * from games where game_name=? limit ?,8";
				psmt = conn.prepareStatement(sql);
				psmt.setString(1, namevalue);
				psmt.setInt(2, page);
			}

			rs = psmt.executeQuery();
			List<GameList> games = new ArrayList<>();
			while (rs.next()) {
				GameList game = new GameList();
				game.setId(rs.getInt("id"));
				game.setGamename(rs.getString("game_name"));
				game.setPublisher(rs.getString("publisher"));
				game.setAdddate(rs.getString("add_date"));
				game.setIntroduce(rs.getString("introduce"));
				game.setType(rs.getString("type"));
				game.setState(rs.getInt("state"));
				games.add(game);
			}
			return games;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionFactory.close(conn, psmt, rs);
		}
		return null;
	}

	@Override
	public int findTotal() {
		Connection conn = ConnectionFactory.getConnection();
		PreparedStatement psmt = null;
		ResultSet rs = null;
		int total = 0;
		try {

			String sql = "select count(*) as total from games";
			psmt = conn.prepareStatement(sql);
			rs = psmt.executeQuery();
			while (rs.next()) {
				total = rs.getInt("total");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionFactory.close(conn, psmt, rs);
		}
		return total;
	}

}
